package myJs.user.soft.fileSelect

import myJs.Implicits.JArJDS
import myJs.Utils._
import scala.scalajs.js.Dynamic.{global => g}
import myJs.myPkg.jquery.$
import myJs.myPkg.{ColumnOptions, Select2Options, TableOptions}
import myJs.tool.Pojo.{DiffAnaMulSoft, DiffAnaSoft, FilterContentData, OplsdaSoft}
import myJs.tool.Tool
import myJs.user.data.DataManage
import org.scalajs.dom.ext.Ajax
import scalatags.Text.all.{`class`, `type`, a, button, href, target, title}
import myJs.tool.Tool._

import scala.collection.immutable.SeqMap
import scala.scalajs.js
import scala.scalajs.js.annotation.{JSExport, JSExportTopLevel}
import scalatags.Text.all._
import myJs.Implicits._
import scala.scalajs.js.JSConverters._
import org.scalajs.macrotaskexecutor.MacrotaskExecutor.Implicits._

/**
 * Created by yz on 11/8/2020
 */
@JSExportTopLevel("MissionResultSelectTab")
object MissionResultSelectTab {

  val tabId = "missionResult"
  val tableId = "table"

  def tbFmt(columnName: String): js.Function = (v: js.Any, row: js.Dictionary[js.Any]) => columnName match {
    case "kind" => Tool.getShowName(v.toString)
    case "fileName" => {
      val url = g.jsRoutes.controllers.MissionController.viewCsvFileContent().url.toString
      a(href := s"${url}?missionId=${row("id")}&fileName=${v}", target := "_blank", v.toString)
    }
    case _ => v
  }

  lazy val operateColumn = js.Array(
    ColumnOptions.field("operate").title(messages("operations")).formatter(operateFmt).filterControl("clear")
  )

  @JSExport("operateFmt")
  def operateFmt: js.Function = {
    (v: js.Any, row: js.Dictionary[js.Any]) =>
      val folder = row("missionName").toString
      val selectStr = button(`class` := "btn  green btn-xs", title := messages("select"), `type` := "button",
        `class` := "myFileSelectButton", dataFolder := s"mission/${folder}",
        dataFileName := s"${row("fileName").toString}",
        messages("select")
      )
      val rs = List(selectStr)
      rs.mkString("&nbsp;")
  }

  def initFilterContent(tabId: String = "") = {
    val select2SortDatas = List(
      FilterContentData("kind", messages("softName"), List.empty),
    )
    val textSortDatas = List(
      FilterContentData("missionName", messages("taskName")),
    )
    Tool.initFilterContent(parentId = s"${tabId}", select2SortDatas = select2SortDatas, textSortDatas = textSortDatas)
  }

  def refreshSelect2(parentId: String) = {
    refreshKind(parentId)
  }

  def refreshKind(parentId: String) = {
    val inputName = "kind"
    val data = List(OplsdaSoft, DiffAnaSoft, DiffAnaMulSoft).map(_.nameStr)
    val array = (data).map { v =>
      js.Dictionary("text" -> Tool.getShowName(v), "id" -> v)
    }
    val parentJq = $(s"#${parentId}")
    val options = Select2Options(data = array.toJSArray, multiple = true, placeholder = messages("clickToChoose"),
      dropdownParent = parentJq)
    parentJq.findInputByName(inputName).select2(options)
  }

  def initTable = {
    initFilterContent(tabId)
    refreshSelect2(tabId)
    val map = SeqMap("fileName" -> messages("fileName"), "missionName" -> messages("taskName"), "kind" -> messages("softName"), "startTime" -> messages("startTime"),
      "endTime" -> messages("endTime"))
    val columnNames = map.keyList
    val columns = columnNames.map { columnName =>
      val title = map.getOrElse(columnName, columnName)
      val fmt = tbFmt(columnName)
      val basicOptions = ColumnOptions.field(columnName).title(title).sortable(true).formatter(fmt)
      columnName match {
        case x if List("kind", "missionName").contains(x) => basicOptions.
          sortable(false).operateable(true)
        case _ => basicOptions
      }
    }.concat(operateColumn)
    val options = TableOptions.columns(columns.toJSArray).searchOnButton(false).filterControl(false).
      locale(Tool.getBTLanguage)
    $(s"#${tabId} #${tableId}").bootstrapTable(options)
    //    Tool.dateInit
  }

  def tableF = {
    val missionKind = $(".myFileSelect.myCurrent").dataMissionKind
    val fileName = Tool.getInputByName("file").myVal
    println(fileName)
    val url = g.jsRoutes.controllers.MissionController.getAllMissionResult().url.toString
    Ajax.get(url = s"${url.noCache}&kind=${missionKind}&fileName=${fileName}", headers = Map("Content-Type" -> "application/json")).map { xhr =>
      xhr.responseText.toJArJDJAn.toMyJDS
    }
  }

  @JSExport("refreshTable")
  def refreshTable(f: JArJDS => js.Any = (myData) => ()) = {
    val queryMap = Tool.getQueryMap(tabId)
    println(queryMap)
    tableF.map { data =>
      val sortData = DataManage.sortExec(data, queryMap)

      def loopFilter(sortData: JArJDS) = {

        val filterColumns = queryMap.removedAll(List("sort", "order")).filter(_._2.map(_.trim).nonEmpty).keyList

        def loop(acc: JArJDS, elems: List[String]): JArJDS = {
          elems match {
            case Nil => acc
            case y :: ys =>
              val searchV = queryMap(y)
              val vs = searchV
              val trueSearchV = searchV.head
              val fieldName = y.split("\\.")(0)
              val name = y.split("\\.")(1)
              val jq = $(s"#${fieldName}Content").findInputByName(name)
              val curFilterData = if (jq.hasClass("myDatepicker")) {
                acc.filter { row =>
                  val dbDate = row(fieldName)
                  if (name == "startTime") {
                    Tool.timeBefore(vs.head, dbDate)
                  } else {
                    Tool.timeAfter(vs.head, dbDate)
                  }
                }
              } else if (jq.hasClass("select2MultiInput")) {
                acc.filter { row =>
                  vs.exists(row(fieldName).contains(_))
                }
              } else {
                acc.filter { row =>
                  row(fieldName).contains(vs.head)
                }
              }
              loop(curFilterData, ys)
          }
        }

        loop(sortData, filterColumns)
      }

      val filterData = loopFilter(sortData)
      $(s"#${tabId} #${tableId}").bootstrapTable("load", filterData)
      f(data)
    }
  }


}
